//
//  YFSportAndSensorApi.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/28.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSportAndSensorApi.h"
#import "DeviceInfo.h"
#import "NSString+Extension.h"
#import "NSObject+Until.h"

@implementation YFSportAndSensorApi

+ (instancetype)getServerDeviceVersionWithOemTpe:(OemType)oemType completed:(void(^)(NSString *versionS,NSString *downloadPath,NSError *error))block {
    YFSportAndSensorApi *getVersionApi = [YFSportAndSensorApi requestApiWithType:kDeviceGetDeviceVersion andParam:@{@"oemType":[SquashEnum pidStringWithOemType:oemType]}];
    
    [[YFNetworkingService sharedInstance] sendRequest:getVersionApi callback:^(BOOL success, id result, NSError *error) {
        NSString *version, *path;
        if (success) {
            version = [[result responseInfo] objectForKey:@"Version"];
            path = [[result responseInfo] objectForKey:@"Path"];
        }
        if (block) {
            block(version,path,error);
        }
    }];
    return getVersionApi;
}


// 上传天运动统计数据
+ (instancetype)uploadDayRecordDataWithItems:(NSArray <YFDayRecordItem *>*)dayItems completed:(void(^)(NSError *error))completed {
    DeviceInfo *sendor = [DeviceInfo getLastDevice];
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:dayItems.count];
    for (YFDayRecordItem *obj in dayItems) {
         [arrM addObject:[obj dayRecordItemToDict]];
    }
    NSDictionary *dict = @{
                           @"mac":[NSString checkIfNullWithString:[sendor macAddress]],
                           @"firmwareVersion":[NSString checkIfNullWithString:[sendor macAddress]],
                           @"data":[NSString dictionaryToJson:arrM.copy],
                           };
    
    YFSportAndSensorApi *api = [YFSportAndSensorApi requestApiWithType:kSportUploadDaySportData andParam:dict];
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        if (completed) {
            completed(error);
        }
    }];
    return api;
}

// 上传天的详情数据
+ (instancetype)uploadDayRecordDetailDataWithDayItem:(NSArray <YFDayRecordItem *>*)dayItems completed:(void(^)(NSError *error))completed {
    NSMutableArray *totalDataArrM = [NSMutableArray array];
    for (YFDayRecordItem *dayItem in dayItems) {
        NSMutableArray *arrM = [NSMutableArray array];
        for (YFSwingDetailItem *swingDetailItem in dayItem.detailItems ) {
            [arrM addObject:[swingDetailItem swingDetailItemToDict]];
        }
        NSDictionary *dict = @{
                               @"Date":dayItem.dayDate,
                               @"Data":arrM.copy,
                               };
        [totalDataArrM addObject:dict];
    }
    
    YFSportAndSensorApi *api = [YFSportAndSensorApi requestApiWithType:kSportUploadDayDetailSportData andParam:@{@"data":[NSString dictionaryToJson:totalDataArrM.copy]}];
    [[YFNetworkingService sharedInstance] sendRequest:api callback:^(BOOL success, id result, NSError *error) {
        if (completed) {
            completed(error);
        }
    }];
    return api;
}

+ (instancetype)getHaveSportDataDays {
    return [YFSportAndSensorApi requestApiWithType:kSportGetHaveSportDataDays andParam:nil];
}

+ (instancetype)getDayStatisticsDataWithDay:(NSString *)day {
   return [YFSportAndSensorApi requestApiWithType:kSportGetDayStatisticsSportData andParam:@{@"date":[NSString checkIfNullWithString:day]}];
}

+ (instancetype)getDayStatisticsDetailWithDay:(NSString *)day {
    YFSportAndSensorApi *api = [YFSportAndSensorApi requestApiWithType:kSportGetDayDetailSportData andParam:@{@"date":[NSString checkIfNullWithString:day]}];
    
    return api;
}

+ (instancetype)getWeekStaticsisDataWithPage:(NSInteger)page completed:(void(^)(BOOL success,NSDictionary *errDescJosn))completedBlock {
    YFSportAndSensorApi *weekApi = [YFSportAndSensorApi requestApiWithType:kSportGetWeekStaticsisData andParam:@{@"page":[NSString checkIfNullWithString:@(page).stringValue]}];
    
    [[YFNetworkingService sharedInstance] sendRequest:weekApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            if (completedBlock) {
                completedBlock(success,[weekApi responseInfo]);
            }
        }else {
            if ([weekApi loadCacheWithError:nil] && [[weekApi responseInfo] isKindOfClass:[NSDictionary class]]) {
                if (completedBlock) {
                    completedBlock(YES,[weekApi responseInfo]);
                }
            }else {
                if (completedBlock) {
                    completedBlock(success,nil);
                }
            }
        }
    }];
    return weekApi;
}

+ (instancetype)getMonthStaticsisDataWithPage:(NSInteger)page completed:(void(^)(BOOL success,NSDictionary *errDescJosn))completedBlock{
    YFSportAndSensorApi *monthApi = [YFSportAndSensorApi requestApiWithType:kSportGetMonthStaticsisData andParam:@{@"page":[NSString checkIfNullWithString:@(page).stringValue]}];
    
    [[YFNetworkingService sharedInstance] sendRequest:monthApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            if (completedBlock) {
                completedBlock(success,[monthApi responseInfo]);
            }
        }else {
            if ([monthApi loadCacheWithError:nil] && [[monthApi responseInfo] isKindOfClass:[NSDictionary class]]) {
                if (completedBlock) {
                    completedBlock(YES,[monthApi responseInfo]);
                }
            }else {
                if (completedBlock) {
                    completedBlock(success,nil);
                }
            }
        }
    }];
    
    return monthApi;
}

+ (instancetype)getYearStaticsisDataWithPage:(NSInteger)page completed:(void(^)(BOOL success,NSDictionary *errDescJosn))completedBlock{
    YFSportAndSensorApi *yearApi = [YFSportAndSensorApi requestApiWithType:kSportGetYearStaticsisData andParam:@{@"page":[NSString checkIfNullWithString:@(page).stringValue]}];
    [[YFNetworkingService sharedInstance] sendRequest:yearApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            if (completedBlock) {
                completedBlock(success,[yearApi responseInfo]);
            }
        }else {
            if ([yearApi loadCacheWithError:nil] && [[yearApi responseInfo] isKindOfClass:[NSDictionary class]]) {
                if (completedBlock) {
                    completedBlock(YES,[yearApi responseInfo]);
                }
            }else {
                if (completedBlock) {
                    completedBlock(success,nil);
                }
            }
        }
    }];
    
    return yearApi;
}


// 设置缓存时间
- (NSInteger)cacheTimeInSeconds {
    if (self.apiType == kSportGetWeekStaticsisData ||
        self.apiType == kSportGetMonthStaticsisData ||
        self.apiType == kSportGetYearStaticsisData) {
        return 600;// 三分钟缓存
    }
    return [super cacheTimeInSeconds];
}


/**
 下载固件包
 */
+ (NSURLSessionDownloadTask *)downLoadFirware:(NSURL *)url
                              downLoadProress:(void (^)(float progress))progress
                                   completion:(void  (^) (NSString *path, NSError *error))completion{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        progress(1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:path];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        // filePath就是下载文件的位置，可以解压，也可以直接拿来使用
        if (completion) {
            completion([filePath path], error? error : nil);
        }
    }];
    
    [task resume];
    return task;
}

/**
 上传模板
 */
+ (void)addTemplateToServer:(YFThreeDTemplate *) uploadTemplate
                 completion:(void(^)(NSString *tempaleID ,NSError *error)) completion;{
    NSDictionary *params = @{@"tplName":uploadTemplate.name,
                             @"type":@(uploadTemplate.selectActionType),
                             @"hand":@(uploadTemplate.handType),
                             @"mac":[User getLastUser].lastDeviceMac,
                             @"createTime":[NSDate date],
                             @"systemType":@"1"};
    NSMutableArray *vx = [NSMutableArray array];
    NSMutableArray *vy = [NSMutableArray array];
    NSMutableArray *vz = [NSMutableArray array];
    for (YFThreeDDetailItem *item in uploadTemplate.threeDItem.threeDDetailItems) {
        [vx addObject:@(item.vx).stringValue];
        [vy addObject:@(item.vy).stringValue];
        [vz addObject:@(item.vz).stringValue];
    }
    NSDictionary *dataJsonDic = @{@"vx":vx.mutableCopy,
                                  @"vy":vy.mutableCopy,
                                  @"vz":vz.mutableCopy,
                                  @"maxSpeedID":@(uploadTemplate.threeDItem.maxSpeedId),
                                  @"startID":@(uploadTemplate.threeDItem.startID),
                                  @"endID":@(uploadTemplate.threeDItem.endID),
                                  @"handDirection":@(uploadTemplate.threeDItem.handType),
                                  @"swingTime":@(uploadTemplate.threeDItem.swingTime),
                                  @"swingSpeed":@(uploadTemplate.threeDItem.swingSpeed),
                                  @"name":uploadTemplate.name,
                                  @"swingPower":@(uploadTemplate.threeDItem.strength),
                                  @"threeDType":@(uploadTemplate.selectActionType)};
    NSString *jsonString = [dataJsonDic convertToJsonData:dataJsonDic];
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    YFSportAndSensorApi *uploadTemplateApi = [YFSportAndSensorApi requestApiWithType:kSportUploadTemplateToServer andParam:params];
    uploadTemplateApi.constructingBodyBlock = ^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data
                                    name:@"userfile"
                                fileName:[NSString stringWithFormat:@"model_ios.txt"]
                                mimeType:@"txt"];
    };
    [[YFNetworkingService sharedInstance] sendRequest:uploadTemplateApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            NSDictionary *dataDic = [result responseInfo];
            if (completion) {
                completion(dataDic[@"TplID"],nil);
            }
        }else if(completion){
            completion(nil,error);
        }
    }];
}

/**
 删除模板
 */
+ (void)deleteTemplateToServer:(NSArray <NSString *> *)deleteIDs
                      complete:(void(^)(NSError *error)) complete{
    if (deleteIDs.count <= 0) {
        if (complete) {
            complete(nil);
        }
        return;
    }
    NSDictionary *params = @{@"tplID":deleteIDs};
    YFSportAndSensorApi *deleteTemplateApi = [YFSportAndSensorApi requestApiWithType:kSportDeleteTemplateToServer andParam:params];
    [[YFNetworkingService sharedInstance] sendRequest:deleteTemplateApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            if (complete) {
                complete(nil);
            }
        }else if(complete){
            complete(error);
        }
    }];
}

@end
